package org.teamh.connection.json.handler;

import org.teamh.connection.json.event.JsonEventObject;
import org.teamh.game.Start;
import org.teamh.logic.datamodel.*;

public class TeamHandler extends JsonMasterHandler {

	public TeamHandler(Start start, DatamodelManager manager) {
		super(start, manager);
	}
	
	public boolean handleMsg(JsonEventObject json) {
		
		if (json.getSource().startsWith("Team")) {
			if (json.getProperty().equals("name")) {
				Team team = manager.getTeam(json.getSource());
				if(team == null) {
					team = new Team(json.getSource());
					manager.addTeam(team);
				}
				team.setName(json.getNewValue());
				return true;
			} else if (json.getProperty().equals("users")) {
				Team team = manager.getTeam(json.getSource());
				if(team == null) {
					team = new Team(json.getProperty());
					manager.addTeam(team);
				}
				
				if(json.getNewValue() != null) {
					User user = manager.getUser(json.getNewValue());
					if(user == null) {
						user = new User(json.getNewValue());
						manager.addUser(user);
						team.addUser(user);
					}
				} else {
					team.removeUser(manager.getUser(json.getOldValue()));
				}
				return true;
			}
			return false;
		} else {
			return false;
		}	
	}
}